package com.nstskj.study.netty.tcp.netty.protocol.session.manage.impl;

import com.nstskj.study.netty.tcp.netty.protocol.event.CloseNetDeviceEvent;
import com.nstskj.study.netty.tcp.netty.protocol.event.CreateNetDeviceEvent;
import com.nstskj.study.netty.tcp.netty.protocol.event.base.AbstractNetDeviceEvent;
import com.nstskj.study.netty.tcp.netty.protocol.session.base.AbstractSession;
import com.nstskj.study.netty.tcp.netty.protocol.session.manage.NetDeviceSessionManage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ZhouChuGang
 * @version 1.0
 * @project nstskj-study-netty-tcp-spring
 * @date 2021/4/21 21:06
 * @Description
 */
@Slf4j
@Component
public class SpringNetDeviceSessionManage implements NetDeviceSessionManage, ApplicationListener<AbstractNetDeviceEvent> {

    private final Map<String, AbstractSession> sessionMap = new ConcurrentHashMap<>();

    /**
     * 得到指定session对象
     *
     * @param sessionId
     * @return
     */
    @Override
    public AbstractSession getSession(String sessionId) {
        return sessionMap.get(sessionId);
    }

    /**
     * 得到所以的会话及其对应信息
     *
     * @return
     */
    @Override
    public Map<String, AbstractSession> getSessionMap() {
        return this.sessionMap;
    }


    /**
     * 收到事件
     *
     * @param netDeviceEvent
     */
    @Override
    public void onApplicationEvent(AbstractNetDeviceEvent netDeviceEvent) {
        AbstractSession abstractSession = netDeviceEvent.getAbstractSession();
        String sessionId = abstractSession.getSessionId();
        if (netDeviceEvent instanceof CreateNetDeviceEvent) {
            //如果为创建事件
            //启动
            log.info("收到创建事件 sessionId {}", sessionId);
            this.sessionMap.put(sessionId, abstractSession);
        } else if (netDeviceEvent instanceof CloseNetDeviceEvent) {
            log.info("收到关闭事件 sessionId {}", sessionId);
            //如果为关闭事件
            AbstractSession session = sessionMap.remove(sessionId);
        }
    }
}
